package com.cans.lightning.business.pms.service.impl;

import com.cans.lightning.business.core.constant.Constants;
import com.cans.lightning.business.pms.service.api.ISendMailService;
import com.cans.lightning.config.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.concurrent.TimeUnit;

/**
 * 邮件发送服务
 *
 * @author cans
 * @date 2021-05-19 14:52
 **/
@Service
public class SendMailServiceImpl implements ISendMailService {

//    @Resource
    private JavaMailSenderImpl mailSender;

    @Autowired
    private RedisCache redisCache;

    @Override
    public boolean sendMail(String toMail, String subject, String content) throws MessagingException {
        MimeMessage messageM = this.mailSender.createMimeMessage();
        MimeMessageHelper message = new MimeMessageHelper(messageM);
        message.setTo(toMail);
        message.setSubject(subject);
        message.setText(content);
        message.setFrom(mailSender.getUsername());
        mailSender.send(messageM);

        // 验证码的KEY
        String key = Constants.EMAIL_RESET_CODE + toMail;
        redisCache.setCacheObject(key, content,5, TimeUnit.MINUTES);

        return Boolean.TRUE;
    }
}
